from flask import jsonify, request
from datetime import datetime
from decimal import Decimal
from commons.controller.base_controller import BaseController
from travel_service.travel.service.schedule_service import ScheduleService


class ScheduleController(BaseController):
    def __init__(self):
        self.schedule_service = ScheduleService()

    def get_schedule_by_id(self):
        """
        根据行程ID获取行程信息。
        """
        # 从请求体解析参数
        data = request.get_json()
        schedule_id = data.get("scheduleId")

        return BaseController.get_success_response(self, self.schedule_service.get_schedule_by_schedule_id(schedule_id))

    def get_schedule_by_travel_id(self):
        """
        根据用户ID获取出差信息。
        """
        # 从请求体解析参数
        data = request.get_json()
        travel_id = data.get("travelId")

        return BaseController.get_success_response(self, self.schedule_service.get_schedule_by_travel_id(travel_id))

    def add_schedule(self):
        """
        添加新的出差记录
        """
        # 从请求体解析参数
        data = request.get_json()

        # 获取并验证必要的参数
        location = data.get("location")
        task = data.get("task")
        schedule_detail = data.get("scheduleDetail")
        start_date_str = data.get("startDate")
        end_date_str = data.get("endDate")

        # 参数验证
        if not all([location,task,schedule_detail,start_date_str,end_date_str]):
            return jsonify({"error": "Missing required fields"}), 400

        try:
            # 转换applyDate为datetime格式
            start_date = datetime.strptime(start_date_str.split(' (')[0], "%a %b %d %Y %H:%M:%S GMT%z")  # Assuming "YYYY-MM-DD" format
            end_date = datetime.strptime(end_date_str.split(' (')[0], "%a %b %d %Y %H:%M:%S GMT%z")  # Assuming "YYYY-MM-DD" format

            # 创建Reimbursement对象
            schedule = {
                "location": location,
                "task": task,
                "schedule_detail": schedule_detail,
                "start_date": start_date,
                "end_date": end_date,
            }

            # 调用服务层添加报销记录
            self.schedule_service.add(schedule)

            # 返回成功响应
            return jsonify({"message": "Reimbursement added successfully"}), 200

        except ValueError as e:
            # 如果日期或数字转换失败
            return jsonify({"error": str(e)}), 400